//
//  UserInformationDatabase.m
//  Double
//
//  Created by dllo on 15/5/26.
//  Copyright (c) 2015年 袁庆秋. All rights reserved.
//

#import "UserInformationDatabase.h"
#import <sqlite3.h>
#import "UserInformationModel.h"
#import "DB.h"

@implementation UserInformationDatabase

+ (void)commitSql:(NSString *)str
{
    sqlite3 * db = [DB openDB];
    int result = sqlite3_exec(db, [str UTF8String], nil, nil, nil);
    if (result == SQLITE_OK) {
        NSLog(@"执行成功");
    } else {
        NSLog(@"执行失败");
    }
    
}

// 插入
+ (void)insertWithModel:(UserInformationModel *)model
{
    NSString * str = [NSString stringWithFormat:@"insert into UserInformation(Num, PassWord) values ('%@', %ld)", model.Num, model.PassWord];
    [UserInformationDatabase commitSql:str];
    NSLog(@"插入成功");
}
// 删除
+ (void)deleteWithModel:(UserInformationModel *)model
{
    NSString * str = [NSString stringWithFormat:@"delete from UserInformation where Num = '%@'", model.Num];
    [UserInformationDatabase commitSql:str];
}

// 更新
+ (void)updataWithModel:(NSString *)Num PassWord:(NSInteger)PassWord
{
    NSString * str = [NSString stringWithFormat:@"updata UserInformation set Num = '%@', PassWord = %ld", Num, PassWord];
    [UserInformationDatabase commitSql:str];
}

+ (NSArray *)selectAll
{
    NSString * str = @"select Num, PassWord from UserInformation";
    sqlite3 * db = [DB openDB];
    // 定义执行结果接收者 + 限制长度 -1 不限长度 &stmt查询结果所在位置
    sqlite3_stmt * stmt = nil;
    int result = sqlite3_prepare_v2(db, [str UTF8String], -1, &stmt, nil);
    NSMutableArray * array = [NSMutableArray array];
    if (result == SQLITE_OK) {
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            int PassWord = sqlite3_column_int(stmt, 1);
            const unsigned char * Num = sqlite3_column_text(stmt, 0);
            // 把C语言字符串转换成oc字符串
            NSString * Name = [NSString stringWithUTF8String:(const char *)Num];
            UserInformationModel * model = [UserInformationModel UserInformationModelWithNum:Name PassWord:PassWord];
            [array addObject:model];
        }
    }
    return array;
}





@end
